<template>
  <div class="p-2 page-flex">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="业主单位" prop="ownerUnit">
              <el-input v-model="queryParams.ownerUnit" placeholder="请输入业主单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目区域" prop="projectRegion">
              <el-cascader v-model="queryParams.projectRegion" :options="searchRegionOptions"
                :props="{ lazy: true, lazyLoad: loadSearchRegion, value: 'value', label: 'label', checkStrictly: true }"
                placeholder="请选择项目区域" style="width: 240px" clearable />
            </el-form-item>
            <el-form-item label="执行总裁" prop="presidentsId">
              <el-select
                :model-value="selectedSearchPresident ? selectedSearchPresident.userName || selectedSearchPresident.nickName : ''"
                placeholder="请选择执行总裁" style="width: 240px" clearable @click="showSearchPresidentSelector = true"
                @clear="clearSearchPresident">
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="showSearchPresidentSelector = true"> 选择执行总裁 </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="签订时间" prop="conSignTime" style="width: 308px">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item label="合同状态" prop="contractStatus">
              <el-select v-model="queryParams.contractStatus" placeholder="请选择合同状态" style="width: 240px" clearable>
                <el-option v-for="item in contract_status" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否逾期" prop="isDelay">
              <el-select v-model="queryParams.isDelay" placeholder="请选择是否逾期" style="width: 240px" clearable>
                <el-option v-for="item in contract_is_delay" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item style="margin-left: auto">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" class="table-card">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['project:contract:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['project:contract:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['project:contract:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown @command="handleMoreCommand"
              v-hasPermi="['project:contract:import', 'project:contract:export']">
              <el-button type="warning" plain size="default">
                导入导出
                <el-icon class="el-icon--right">
                  <ArrowDown />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="download-template">
                    <el-icon style="vertical-align: middle">
                      <Download />
                    </el-icon>
                    <span style="margin-left: 4px">下载模板</span>
                  </el-dropdown-item>
                  <el-dropdown-item command="import-data">
                    <el-icon style="vertical-align: middle">
                      <Upload />
                    </el-icon>
                    <span style="margin-left: 4px">导入数据</span>
                  </el-dropdown-item>
                  <el-dropdown-item command="export-data">
                    <el-icon style="vertical-align: middle">
                      <Download />
                    </el-icon>
                    <span style="margin-left: 4px">导出数据</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Document" @click="() => handleLog()"
              v-hasPermi="['project:contract:logList']">日志查询</el-button>
          </el-col>
          <el-col :span="1.5">
            <div style="display: flex; align-items: center; gap: 8px">
              <el-select v-model="sortField" placeholder="请选择排序字段" style="width: 170px" clearable
                @change="handleSortChange">
                <el-option label="合同名称" value="contractName" />
                <el-option label="合同编号" value="contractNumber" />
                <el-option label="业主单位" value="ownerUnit" />
                <el-option label="项目区域" value="projectRegion" />
                <el-option label="执行总裁" value="presidentsId" />
                <el-option label="合同签订时间" value="conSignTime" />
                <el-option label="合同约定完成时间" value="conEndTime" />
                <el-option label="合同是否有延期约定" value="hasExtension" />
                <el-option label="合同状态" value="contractStatus" />
                <el-option label="合同拆分状态" value="splitStatus" />
                <el-option label="修改时间" value="updateTime" />
                <el-option label="是否逾期" value="isDelay" />
              </el-select>
              <el-button v-if="sortField" :icon="sortOrder === 'asc' ? 'ArrowUp' : 'ArrowDown'" @click="toggleSortOrder"
                type="info" plain size="small" :title="sortOrder === 'asc' ? '当前为正序，点击切换为逆序' : '当前为逆序，点击切换为正序'">
                {{ sortOrder === 'asc' ? '正序' : '逆序' }}
              </el-button>
            </div>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="proContractList" @selection-change="handleSelectionChange" border :header-cell-style="{'text-align':'center'}"
        height="100%" class="flex-table">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="55">
          <template #default="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="主键ID" align="center" prop="id" v-if="false" width="5"/>
        <el-table-column label="合同名称" align="left" prop="contractName" show-overflow-tooltip width="400"/>
        <el-table-column label="合同编号" align="center" prop="contractNumber" show-overflow-tooltip  width="100"/>
        <el-table-column label="业主单位" align="center" prop="ownerUnit" show-overflow-tooltip  width="100"/>
        <el-table-column label="项目区域" align="center" prop="projectRegionName" show-overflow-tooltip  width="100"/>
        <el-table-column label="执行总裁" align="center" prop="presidentsName" show-overflow-tooltip width="120"/>
        <el-table-column label="合同签订时间" align="center" prop="conSignTime" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.conSignTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同约定完成时间" align="center" prop="conSignTime" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.conEndTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否有延期约定" align="center" prop="hasExtension" width="80">
          <template #default="scope">
            <dict-tag :options="contract_extension" :value="scope.row.hasExtension" />
          </template>
        </el-table-column>
        <el-table-column label="合同状态" align="center" prop="contractStatus" width="80">
          <template #default="scope">
            <dict-tag :options="contract_status" :value="scope.row.contractStatus || ''" />
          </template>
        </el-table-column>
        <el-table-column label="合同拆分状态" align="center" prop="splitStatus" width="80">
          <template #default="scope">
            <dict-tag :options="contract_split_status" :value="scope.row.splitStatus || ''" />
          </template>
        </el-table-column>
        <el-table-column label="是否逾期" align="center" prop="isDelay" width="80">
          <template #default="scope">
            <dict-tag :options="contract_is_delay" :value="scope.row.isDelay || ''" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['project:contract:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['project:contract:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="预览" placement="top">
              <el-button link type="primary" icon="View" @click="handlePreview(scope.row)"
                v-hasPermi="['project:contract:query']"></el-button>
            </el-tooltip>
            <el-tooltip content="查看日志" placement="top">
              <el-button link type="info" icon="Document" @click="() => handleLog(scope.row)"
                v-hasPermi="['project:contract:logList']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container" v-show="total > 0">
        <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]" @pagination="getList" />
      </div>
    </el-card>
    <!-- 添加或修改合同信息对话框 -->
    <el-dialog :title="dialog.title" :model-value="dialog.visible" @update:model-value="(val) => (dialog.visible = val)"
      width="900px" append-to-body>
      <template #default>
        <div style="padding-right: 24px">
          <el-form ref="formRef" :model="form" label-width="140px" label-position="left"
            style="padding: 20px 0 20px 24px">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="合同名称" prop="contractName">
                  <el-input v-model="form.contractName" placeholder="请输入合同名称" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同编号" prop="contractNumber">
                  <el-input v-model="form.contractNumber" placeholder="请输入合同编号" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="业主单位" prop="ownerUnit">
                  <el-input v-model="form.ownerUnit" placeholder="请输入业主单位" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目区域" prop="projectRegion">
                  <el-cascader v-model="form.projectRegion" :options="regionOptions"
                    :props="{ lazy: true, lazyLoad: loadRegion, value: 'value', label: 'label', checkStrictly: true }"
                    :placeholder="regionPlaceholder" style="width: 100%" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目执行总裁" prop="presidentsId">
                  <div class="user-selector-container">
                    <div class="selected-users" v-if="selectedPresidents.length > 0">
                      <el-tag v-for="president in selectedPresidents" :key="president.userId" closable
                        @close="removePresident(president)" type="primary"
                        style="margin-right: 8px; margin-bottom: 4px">
                        {{ president.userName || president.nickName }}
                      </el-tag>
                    </div>
                    <el-button type="primary" plain @click="showPresidentSelector = true" style="width: 100%">
                      {{ selectedPresidents.length > 0 ? '重新选择执行总裁' : '选择执行总裁' }}
                    </el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同签订时间" prop="conSignTime">
                  <el-date-picker clearable v-model="form.conSignTime" type="date" value-format="YYYY-MM-DD"
                    placeholder="请选择合同签订日期" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同约定工期" prop="conPeriod">
                  <el-input v-model="form.conPeriod" type="textarea" :rows="6" placeholder="请输入合同约定工期"
                    style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同约定完成时间" prop="conEndTime">
                  <el-date-picker clearable v-model="form.conEndTime" type="date" value-format="YYYY-MM-DD"
                    placeholder="请选择合同约定完成时间" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同约定工作内容" prop="conWorkContent">
                  <el-input v-model="form.conWorkContent" type="textarea" :rows="6" placeholder="请输入合同约定工作内容"
                    style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目约定质量标准" prop="conQualityStandard">
                  <el-input v-model="form.conQualityStandard" type="textarea" :rows="6" placeholder="请输入项目约定质量标准"
                    style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同金额" prop="conAmount">
                  <el-input v-model="form.conAmount" placeholder="请输入合同金额（保留两位小数）" style="width: 100%"
                    @input="handleAmountInput">
                    <template #append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同金额备注" prop="conAmountRemark">
                  <el-input v-model="form.conAmountRemark" type="textarea" :rows="6" placeholder="请输入合同金额备注"
                    style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="付款方式" prop="paymentMethod">
                  <el-input v-model="form.paymentMethod" type="textarea" :rows="6" placeholder="请输入付款方式"
                    style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同是否有延期约定" prop="hasExtension">
                  <el-select v-model="form.hasExtension" placeholder="请选择">
                    <el-option v-for="item in contract_extension" :key="item.value" :label="item.label"
                      :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同延期约定内容" prop="extensionContent">
                  <el-input v-model="form.extensionContent" type="textarea" :rows="6" placeholder="请输入合同延期约定内容"
                    style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="是否逾期" prop="isDelay">
                  <dict-tag :options="contract_is_delay" :value="form.isDelay" style="font-size: 16px" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同状态" prop="contractStatus">
                  <el-select v-model="form.contractStatus" placeholder="请选择合同状态">
                    <el-option v-for="item in contract_status" :key="item.value" :label="item.label"
                      :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" type="textarea" :rows="6" placeholder="请输入备注" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 合同详情对话框 -->
    <el-dialog title="合同详情" v-model="showContractDetail" width="900px" append-to-body>
      <template #default>
        <div style="padding: 20px 0 20px 24px; padding-right: 24px">
          <el-form :model="currentContract" label-width="140px" label-position="left" style="width: 100%">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="合同名称">
                  <el-input v-model="currentContract.contractName" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同编号">
                  <el-input v-model="currentContract.contractNumber" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="业主单位">
                  <el-input v-model="currentContract.ownerUnit" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目区域">
                  <el-input v-model="currentContract.projectRegionName" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目执行总裁">
                  <el-input v-model="currentContract.presidentsName" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同签订时间">
                  <el-input v-model="currentContract.conSignTime" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同约定工期">
                  <el-input v-model="currentContract.conPeriod" type="textarea" :rows="4" style="width: 100%"
                    readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同约定完成时间">
                  <el-input v-model="currentContract.conEndTime" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同约定工作内容">
                  <el-input v-model="currentContract.conWorkContent" type="textarea" :rows="6" style="width: 100%"
                    readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目约定质量标准">
                  <el-input v-model="currentContract.conQualityStandard" type="textarea" :rows="6" style="width: 100%"
                    readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同总金额">
                  <el-input v-model="currentContract.conAmount" style="width: 100%" readonly>
                    <template #append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同金额备注">
                  <el-input v-model="currentContract.conAmountRemark" type="textarea" :rows="3" style="width: 100%"
                    readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="付款方式">
                  <el-input v-model="currentContract.paymentMethod" type="textarea" :rows="6" style="width: 100%"
                    readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同是否有延期约定">
                  <dict-tag :options="contract_extension" :value="currentContract.hasExtension" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同延期约定内容">
                  <el-input v-model="currentContract.extensionContent" type="textarea" :rows="4" style="width: 100%"
                    readonly />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="是否逾期">
                  <dict-tag :options="contract_is_delay" :value="currentContract.isDelay" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="合同状态">
                  <dict-tag :options="contract_status" :value="currentContract.contractStatus" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注">
                  <el-input v-model="currentContract.remark" type="textarea" :rows="4" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="创建人">
                  <el-input v-model="currentContract.createBy" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="创建时间">
                  <el-input
                    :value="currentContract.createTime ? parseTime(currentContract.createTime, '{y}-{m}-{d} {h}:{i}:{s}') : ''"
                    style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="修改人">
                  <el-input v-model="currentContract.updateBy" style="width: 100%" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="修改时间">
                  <el-input
                    :value="currentContract.updateTime ? parseTime(currentContract.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') : ''"
                    style="width: 100%" readonly />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showContractDetail = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 搜索条件用的总裁选择器 -->
    <UserSelector v-model:visible="showSearchPresidentSelector" title="选择执行总裁"
      :selected-user-ids="queryParams?.presidentsId" :selected-user-names="selectedSearchPresidentName"
      :multiple="false" @confirmWithIds="handleSearchPresidentConfirm" @cancel="handleSearchPresidentCancel" />

    <!-- UserSelector 组件 -->
    <UserSelector v-model:visible="showPresidentSelector" title="选择项目执行总裁" :selected-user-ids="form?.presidentsId"
      :selected-user-names="form?.presidentsName" :multiple="true" @confirmWithIds="handlePresidentConfirmWithIds"
      @cancel="handlePresidentCancel" />

    <!-- 导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="handleImportTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProContract" lang="ts">
import { ProContractVO, ProContractQuery, ProContractForm } from '@/api/project/init/contract/types';
import { listProContract, getProContract, delProContract, addProContract, updateProContract } from '@/api/project/init/contract';
import { listAddressByParent } from '@/api/project/init/address';
import { useRouter } from 'vue-router';
import { ArrowDown, Download, Upload } from '@element-plus/icons-vue';
import { globalHeaders } from '@/utils/request';
import { UploadFilled } from '@element-plus/icons-vue';
import { parseTime } from '@/utils/ruoyi';
import { checkContractStatus } from '@/utils/permission';
const router = useRouter();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const proContractList = ref<ProContractVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const showContractDetail = ref(false);
const currentContract = ref<ProContractForm>({} as ProContractForm);

// 表单引用
const formRef = ref<ElFormInstance>();

// 项目区域级联选择相关
const regionOptions = ref([]);
const regionPlaceholder = ref('请选择项目区域');

// 搜索条件区域选择相关
const searchRegionOptions = ref([]);

// 项目执行总裁选择相关
const showPresidentSelector = ref(false);
const selectedPresidents = ref([]);

// 搜索条件总裁选择相关
const showSearchPresidentSelector = ref(false);
const selectedSearchPresident = ref(null);
const selectedSearchPresidentName = ref('');

// 排序相关
const sortField = ref<string | undefined>(undefined);
const sortOrder = ref<string>('asc'); // 设置默认为正序

// 文件上传相关
const uploadRef = ref();
const upload = reactive({
  open: false,
  title: '',
  isUploading: false,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/pro/contract/import'
});

const initFormData: ProContractForm = {
  id: undefined,
  contractName: '',
  contractNumber: '',
  ownerUnit: '',
  projectRegion: '',
  presidentsId: '',
  conSignTime: '',
  conPeriod: '',
  conEndTime: '',
  conWorkContent: '',
  conQualityStandard: '',
  conAmount: '',
  conAmountRemark: '',
  paymentMethod: '',
  hasExtension: '',
  extensionContent: '',
  remark: '',
  splitStatus: '0',
  contractStatus: '',
  isDelay: '0'
};
const data = reactive<PageData<ProContractForm, ProContractQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    contractName: '',
    ownerUnit: '',
    presidentsId: '',
    projectRegion: '',
    contractStatus: '',
    isDelay: '',
    params: {}
  },
  rules: {}
});

const { queryParams, form } = toRefs(data);

const { contract_extension, contract_status, contract_is_delay, contract_split_status } = toRefs<any>(
  proxy?.useDict('contract_extension', 'contract_status', 'contract_is_delay', 'contract_split_status')
);

// 处理总裁选择确认
const handlePresidentConfirmWithIds = (data) => {
  selectedPresidents.value = [...data.users];

  if (form.value) {
    form.value.presidentsId = data.userIds || '';
    form.value.presidentsName = data.userNames || '';
  }

  showPresidentSelector.value = false;
};

// 取消选择总裁
const handlePresidentCancel = () => {
  showPresidentSelector.value = false;
};

// 处理搜索条件总裁选择确认
const handleSearchPresidentConfirm = (data) => {
  if (data.users && data.users.length > 0) {
    selectedSearchPresident.value = data.users[0];
    selectedSearchPresidentName.value = data.userNames || '';

    if (queryParams.value) {
      queryParams.value.presidentsId = data.userIds || '';
    }
  } else {
    selectedSearchPresident.value = null;
    selectedSearchPresidentName.value = '';
    if (queryParams.value) {
      queryParams.value.presidentsId = '';
    }
  }

  showSearchPresidentSelector.value = false;
};

// 取消搜索条件总裁选择
const handleSearchPresidentCancel = () => {
  showSearchPresidentSelector.value = false;
};

// 清空搜索条件总裁选择
const clearSearchPresident = () => {
  selectedSearchPresident.value = null;
  selectedSearchPresidentName.value = '';
  if (queryParams.value) {
    queryParams.value.presidentsId = '';
  }
};

// 移除单个总裁
const removePresident = (president) => {
  const newPresidents = selectedPresidents.value.filter((p) => p.userId !== president.userId);
  selectedPresidents.value = newPresidents;

  if (form.value) {
    const userIds = newPresidents.map((user) => user.userId);
    const userNames = newPresidents.map((user) => user.userName || user.nickName);

    form.value.presidentsId = userIds.length > 0 ? userIds.join(',') : '';
    form.value.presidentsName = userNames.length > 0 ? userNames.join(',') : '';
  }
};

// 区域数据加载（用于表单）
const loadRegion = async (node, resolve) => {
  try {
    // 确保 parentId 是有效的数字，默认为 0
    let parentId = 0;
    if (node && typeof node.value === 'number') {
      parentId = node.value;
    } else if (node && node.value !== undefined && node.value !== null) {
      const parsed = parseInt(String(node.value), 10);
      if (!isNaN(parsed)) {
        parentId = parsed;
      }
    }

    const res = await listAddressByParent(parentId);
    const data = res.data || [];
    resolve(
      data.map((item) => ({
        value: item.id,
        label: item.name,
        leaf: false
      }))
    );
  } catch (error) {
    console.error('加载区域数据失败:', error);
    resolve([]);
  }
};

// 搜索条件区域数据加载
const loadSearchRegion = async (node, resolve) => {
  try {
    // 确保 parentId 是有效的数字，默认为 0
    let parentId = 0;
    if (node && typeof node.value === 'number') {
      parentId = node.value;
    } else if (node && node.value !== undefined && node.value !== null) {
      const parsed = parseInt(String(node.value), 10);
      if (!isNaN(parsed)) {
        parentId = parsed;
      }
    }

    const res = await listAddressByParent(parentId);
    const data = res.data || [];
    resolve(
      data.map((item) => ({
        value: item.id,
        label: item.name,
        leaf: false
      }))
    );
  } catch (error) {
    console.error('加载搜索区域数据失败:', error);
    resolve([]);
  }
};

// 初始化总裁数据
const initPresidents = () => {
  const presidentsId = form.value?.presidentsId;
  const presidentsName = form.value?.presidentsName;

  if (!presidentsId || presidentsId === '') {
    selectedPresidents.value = [];
    return;
  }

  // 使用姓名数据构建显示
  if (presidentsName) {
    const ids = presidentsId
      .split(',')
      .map((id) => id.trim())
      .filter((id) => id);
    const names = presidentsName
      .split(',')
      .map((name) => name.trim())
      .filter((name) => name);

    if (ids.length === names.length) {
      const quickPresidents = ids.map((id, index) => ({
        userId: id,
        userName: names[index],
        nickName: names[index],
        deptName: '项目执行总裁',
        avatar: ''
      }));

      selectedPresidents.value = quickPresidents;
      return;
    }
  }

  // 如果没有姓名数据，使用ID创建简单显示
  const ids = presidentsId
    .split(',')
    .map((id) => id.trim())
    .filter((id) => id);

  selectedPresidents.value = ids.map((id) => ({
    userId: id,
    userName: `用户${id}`,
    nickName: `用户${id}`,
    deptName: '项目执行总裁',
    avatar: ''
  }));
};

// 处理金额输入格式化
const handleAmountInput = (value) => {
  if (!value) return;

  // 只允许数字和小数点
  let formattedValue = value.replace(/[^\d.]/g, '');

  // 确保只有一个小数点
  const parts = formattedValue.split('.');
  if (parts.length > 2) {
    formattedValue = parts[0] + '.' + parts.slice(1).join('');
  }

  // 限制小数点后最多两位
  if (parts.length === 2 && parts[1].length > 2) {
    formattedValue = parts[0] + '.' + parts[1].substring(0, 2);
  }

  // 更新表单值
  if (form.value) {
    form.value.conAmount = formattedValue;
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    const submitData = {
      ...form.value,
      projectRegion: Array.isArray(form.value.projectRegion) ? form.value.projectRegion.join(',') : form.value.projectRegion,
      presidentsId: form.value.presidentsId || '',
      presidentsName: form.value.presidentsName || '',
      conAmount: form.value.conAmount ? parseFloat(String(form.value.conAmount)) : null,
      isDelay: form.value.isDelay || '0',
      createBy: null,
      createTime: null,
      updateBy: null,
      updateTime: null,
      projectRegionName: null
    };
    const action = form.value.id ? updateProContract : addProContract;
    await action(submitData);
    proxy?.$modal.msgSuccess(form.value.id ? '修改成功' : '新增成功');
    dialog.visible = false;
    await getList();
  } catch (error) {
    console.error('提交失败:', error);
    proxy?.$modal.msgError('操作失败，请重试');
  }
};

// 取消操作
const handleCancel = () => {
  dialog.visible = false;
};

// 自动计算逾期状态
const calculateIsDelay = () => {
  // 只有当合同延期约定为否(0)时才自动计算
  if (form.value.hasExtension === '0' && form.value.conEndTime) {
    const endTime = new Date(form.value.conEndTime);
    const currentTime = new Date();

    // 如果当前时间已经超过了合同约定结束时间，则设置为逾期(1)
    if (currentTime > endTime) {
      form.value.isDelay = '1';
    } else {
      form.value.isDelay = '0';
    }
  }
};

/** 查询合同信息列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    // 优化：直接使用addDateRange工具方法处理签订时间范围
    proxy?.addDateRange(params, dateRange.value, 'SignTime');
    // 处理项目区域参数
    if (params.projectRegion && Array.isArray(params.projectRegion)) {
      params.projectRegion = params.projectRegion.join(',');
    }
    // 处理排序参数 - 直接设置到PageQuery中
    if (sortField.value && sortOrder.value) {
      params.orderByColumn = sortField.value;
      params.isAsc = sortOrder.value;
    }
    const res = await listProContract(params);
    proContractList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  // 重置后重新计算逾期状态
  nextTick(() => {
    calculateIsDelay();
  });
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  // 重置搜索条件总裁选择
  selectedSearchPresident.value = null;
  selectedSearchPresidentName.value = '';
  // 重置排序条件
  sortField.value = undefined;
  sortOrder.value = undefined;
  queryFormRef.value?.resetFields();
  queryParams.value.params = {};
  // 重置查询参数中的新字段
  queryParams.value.presidentsId = undefined;
  queryParams.value.projectRegion = undefined;
  queryParams.value.contractStatus = undefined;
  handleQuery();
};

// 处理排序变化
const handleSortChange = () => {
  // 如果选择了排序字段但没有选择排序顺序，则设置默认值
  if (sortField.value && !sortOrder.value) {
    sortOrder.value = 'asc';
  }
  handleQuery();
};

// 切换排序顺序
const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProContractVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  form.value.projectRegion = '';
  dialog.visible = true;
  dialog.title = '添加合同信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ProContractVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getProContract(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改合同信息';
};

/** 删除按钮操作 */
const handleDelete = async (row?: ProContractVO) => {
  const _ids = row?.id || ids.value;
  try {
    await proxy?.$modal.confirm('是否确认删除合同信息编号为"' + _ids + '"的数据项？');
    const res = await delProContract(_ids);
    if (res.code === 200) {
      proxy?.$modal.msgSuccess('删除成功');
      await getList();
    } else {
      proxy?.$modal.msgError(res.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除失败:', error);
    // 用户取消删除不显示错误
    if (error !== 'cancel') {
      proxy?.$modal.msgError('操作失败');
    }
  }
};

/**
 * 下载导入模板
 */
const handleImportTemplate = () => {
  proxy?.download('pro/contract/importTemplate', {}, `contract_template_${new Date().getTime()}.xlsx`);
};

const handleMoreCommand = (command: string) => {
  if (command === 'download-template') {
    handleImportTemplate();
  } else if (command === 'import-data') {
    upload.title = '合同信息导入';
    upload.open = true;
  } else if (command === 'export-data') {
    proxy?.download(
      'pro/contract/export',
      {
        ...queryParams.value
      },
      `pro_contract_${new Date().getTime()}.xlsx`
    );
  }
};

/** 文件上传中处理 */
const handleFileUploadProgress = (event: any, file: any) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: any) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value.clearFiles();
  // 导出结果弹出
  ElMessageBox.alert(response.msg, '导入结果', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确定',
    type: 'info'
  });
  getList();
};

/** 提交上传文件 */
const submitFileForm = () => {
  uploadRef.value.submit();
};

const handlePreview = async (row: ProContractVO) => {
  try {
    const res = await getProContract(row.id);
    currentContract.value = res.data;
    showContractDetail.value = true;
  } catch (error) {
    console.error('获取合同详情失败:', error);
    proxy?.$modal.msgError('获取合同详情失败');
  }
};

const handleLog = (row?: ProContractVO) => {
  if (row && row.id) {
    router.push({ path: `/project/contract-log/index/${row.id}` });
  } else {
    router.push({ path: `/project/contract-log/index/0` });
  }
};

// 监听对话框打开状态
watch(
  () => dialog.visible,
  (visible) => {
    if (visible) {
      nextTick(() => {
        initPresidents();
        calculateIsDelay();
      });
    } else {
      showPresidentSelector.value = false;
      formRef.value?.resetFields();
      selectedPresidents.value = [];
    }
  },
  { immediate: true }
);

// 监听区域名称变化
watch(
  () => [form.value.projectRegionName, dialog.visible],
  ([name, visible]) => {
    if (visible) {
      regionPlaceholder.value = (typeof name === 'string' ? name : '') || '请选择项目区域';
    }
  },
  { immediate: true }
);

// 监听合同约定结束时间和延期约定变化，自动计算逾期状态
watch(
  () => [form.value.conEndTime, form.value.hasExtension],
  () => {
    calculateIsDelay();
  }
);

onMounted(async () => {
  // 初始页面数据
  getList();
});
</script>

<style scoped>
/* 页面弹性布局 */
.page-flex {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 16px);
}

.table-card {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.table-card :deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.flex-table {
  flex: 1;
}

.pagination-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 8px;
}

:deep(.el-descriptions__body) {
  width: 100%;
}

:deep(.el-descriptions__cell) {
  padding: 12px;
}

:deep(.el-descriptions-item__content) {
  word-break: break-word;
}

/* 合同对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

.user-selector-container .el-button {
  width: 100%;
}

/* 只读模式样式 */
.readonly-form :deep(.el-input__inner) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

.readonly-form :deep(.el-textarea__inner) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 32px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-selector-container .selected-users {
    max-height: 80px;
    overflow-y: auto;
  }
}
</style>
